package com.collectplus.express.view;

import android.annotation.SuppressLint;
import android.content.Context;
import android.util.AttributeSet;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.FrameLayout;

/**
 * 解决以下layout中存在的问题<br>
 * FrameLayout android:layout_width="wrap_content" <br>
 * ----ImageView android:layout_width="wrap_content" <br>
 * ----Button android:layout_width="match-parent"<br>
 * 
 * 其中ImageView的宽度比较大,FrameLayout的宽度根据ImageView的宽度一致<br>
 * 但是Button的宽度无法撑满, 只有wrap-content的大小
 * 
 * @author coffee<br>
 *         2015-10-21下午5:21:49
 */
@SuppressLint("AppCompatCustomView")
public class MatchParentButton extends Button {

	public MatchParentButton(Context context) {
		super(context);
	}

	public MatchParentButton(Context context, AttributeSet attrs) {
		super(context, attrs);
	}

	public MatchParentButton(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
	}

	@Override
	protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
		setMeasuredDimension(getDefaultSize(0, widthMeasureSpec), getDefaultSize(0, heightMeasureSpec));
		ViewGroup parent = ((ViewGroup) getParent());
		// 组件的宽度由父类的定
		int viewWidth = parent.getMeasuredWidth() - parent.getPaddingLeft() - parent.getPaddingRight();
		ViewGroup.LayoutParams params = getLayoutParams(); 
		if (params instanceof FrameLayout.LayoutParams) {
			FrameLayout.LayoutParams frameParams = (FrameLayout.LayoutParams) params;
			viewWidth -= (frameParams.leftMargin + frameParams.rightMargin);
		}
		widthMeasureSpec = MeasureSpec.makeMeasureSpec(viewWidth, MeasureSpec.EXACTLY);
		// 精确计算高度
		super.onMeasure(widthMeasureSpec, heightMeasureSpec);
	}
}
